package cn.sun.service.impl;

import cn.sun.domain.Order;
import cn.sun.domain.Product;
import cn.sun.feign.IProductFeignService;
import cn.sun.mapper.OrderMapper;
import cn.sun.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    private final RestTemplate restTemplate;
    private final DiscoveryClient discoveryClient;
    private final IProductFeignService productFeignService;

    @Override
    public Order createOrder(Long pid, Long uid) {
        // Product product = restTemplate.getForObject("http://localhost:8081/product/"+pid, Product.class);

        // List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        // int index = new Random().nextInt(instances.size());
        // ServiceInstance instance = instances.get(index);
        // String url = String.format("http://%s:%d/product/%d",instance.getHost(),instance.getPort(),pid);
        // log.info("请求商品服务的url: {}",url);
        // Product product = restTemplate.getForObject(url, Product.class);

        Product product = null;
        try {
            product = productFeignService.findById(pid);
            if (product == null){
                throw new RuntimeException("不存在的商品id:"+pid);
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
        Order order = new Order();
        order.setUid(uid);
        order.setUsername("阿三");
        order.setPid(pid);
        order.setProductName(product.getName());
        order.setProductPrice(product.getPrice());
        order.setNumber(1);
        this.save(order);
        return order;
    }
}
